package models

import (
	"errors"
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

func WithMysql(hand func(db *gorm.DB) error) error {
	dsn := "root:123456@tcp(127.0.0.1:3306)/take?charset=utf8mb4&parseTime=True&loc=Local"

	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})

	if err != nil {
		return errors.New("mysql client failed,error: " + err.Error())
	}
	fmt.Println("mysql connection successful")

	defer func() {
		dd, _ := db.DB()
		dd.Close()
	}()
	return hand(db)
}

func Migrate() error {
	return WithMysql(func(db *gorm.DB) error {
		return db.AutoMigrate(&Order{})
	})
}
